package org.common.utils.thread;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.concurrent.*;

/**
 * 线程工具
 * @author zhouzhibing
 * @date 2025/2/21
 */
public class ThreadTool {

    /**
     * 获取CPU数量
     */
    public static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();

    /**
     * 默认hash线程池
     */
    private static final ThreadHashPool DEFAULT_THREAD_HASH_POOL = new ThreadHashPool("default");

    /**
     * 默认线程执行器
     */
    private static final ThreadExecutor DEFAULT_THREAD_EXECUTOR = new ThreadExecutor("default-thread-executor");

    /**
     * 根据ID hash执行内容
     * @param id hash计算的ID
     * @param runnable 执行内容
     */
    public static void execute(int id , Runnable runnable) {
        DEFAULT_THREAD_HASH_POOL.execute(id , runnable);
    }

    /**
     * 根据ID hash执行内容
     * @param id hash计算的ID
     * @param callable 执行内容
     * @return 处理对象
     */
    public static <T> Future<T> submit(int id , Callable<T> callable) {
        return DEFAULT_THREAD_HASH_POOL.submit(id , callable);
    }

    /**
     * 线程休眠
     * @param sleep 休眠时间，单位毫秒。
     */
    public static void sleep(long sleep) {
        try {
            Thread.sleep(sleep);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取CPU数量
     * @return CPU数量
     */
    public static int getCpuCount() {
        return CPU_COUNT;
    }

    /**
     * 获取默认线程执行器
     * @return 获取默认线程执行器
     */
    public static ThreadExecutor getDefaultExecutor() {
        return DEFAULT_THREAD_EXECUTOR;
    }


    /**
     * 根据名称，创建一个默认配置的线程池
     * @param name 线程池名称
     * @return 线程池
     */
    public static ThreadPoolExecutor newThreadPoolExecutor(String name) {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                ThreadTool.CPU_COUNT,
                ThreadTool.CPU_COUNT * 2,
                5_000L,
                TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(ThreadTool.CPU_COUNT * 1000),
                new DefaultThreadFactory(name));
//        threadPoolExecutor.allowCoreThreadTimeOut(true);
        return threadPoolExecutor;
    }

    /**
     * 获取异常信息
     * @param e 异常对象
     * @return 异常信息
     */
    public static String toExceptionString(Throwable e) {
        if (e == null) {
            return null;
        }

        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        return sw.toString();
    }
}
